﻿using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace AccumulateApp.Behavior
{
    public static class VirtualKeyboardBehavior
    {
        #region Win32 API 声明
        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern bool PostMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);

        private const uint WM_SYSCOMMAND = 0x0112;
        private const int SC_CLOSE = 0xF060;
        #endregion

        public static readonly DependencyProperty EnableVirtualKeyboardProperty =
            DependencyProperty.RegisterAttached(
                "EnableVirtualKeyboard",
                typeof(bool),
                typeof(VirtualKeyboardBehavior),
                new PropertyMetadata(false, OnEnableVirtualKeyboardChanged));

        public static bool GetEnableVirtualKeyboard(DependencyObject obj)
        {
            return (bool)obj.GetValue(EnableVirtualKeyboardProperty);
        }

        public static void SetEnableVirtualKeyboard(DependencyObject obj, bool value)
        {
            obj.SetValue(EnableVirtualKeyboardProperty, value);
        }

        private static void OnEnableVirtualKeyboardChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is System.Windows.Controls.TextBox textBox)
            {
                if ((bool)e.NewValue)
                {
                    textBox.GotFocus += TextBox_GotFocus;
                    textBox.LostFocus += TextBox_LostFocus;
                }
                else
                {
                    textBox.GotFocus -= TextBox_GotFocus;
                    textBox.LostFocus -= TextBox_LostFocus;
                }
            }
        }

        private static void TextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            string[] possiblePaths = new[]
           {
                System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles), @"Microsoft Shared\ink\TabTip.exe"),
                System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFilesX86), @"Microsoft Shared\ink\TabTip.exe")
            };

            foreach (var path in possiblePaths)
            {
                if (File.Exists(path))
                {
                    // 关键修改：使用UseShellExecute启动进程
                    Process.Start(new ProcessStartInfo
                    {
                        FileName = path,
                        UseShellExecute = true // 确保通过Shell执行，避免权限问题
                    });
                    return;
                }
            }
        }

        private static void TextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            // 查找虚拟键盘窗口
            IntPtr keyboardWnd = FindWindow("IPTip_Main_Window", null);
            if (keyboardWnd != IntPtr.Zero)
            {
                // 发送关闭消息
                PostMessage(keyboardWnd, WM_SYSCOMMAND, SC_CLOSE, 0);
            }
        }
    }
}
